package com.classroommanagesystem.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.classroommanagesystem.domain.entity.User;
import com.classroommanagesystem.exception.BusinessException;
import com.classroommanagesystem.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 自定义UserDetailsService，用于替换内存用户认证。
 * @author victory
 * @date 2025/10/26 10:46
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getStatus, 1);

        User user = userMapper.selectOne(queryWrapper);
        if (user == null)
            throw new UsernameNotFoundException("用户不存在");

        String roleName = RoleConvertUtil.convertRole(user.getRoleId());

        return org.springframework.security.core.userdetails.User.withUsername(user.getUsername())
                .password(user.getPassword())
                .authorities(roleName)
                .build();
    }

}
